package next.fire.spinus.logx.provider.aliyun.client;

import com.alibaba.fastjson.JSONObject;
import next.fire.spinus.logx.provider.aliyun.protobuf.*;

import java.util.List;
import java.util.Map;

/**
 * Created by daibing on 2020/9/15.
 */
public class AliyunLogPbClient extends AliyunLogClient {
    public static final String LOG_TOPIC = "logTopic";
    public static final String LOG_SOURCE = "logSource";
    public static final String LOG_ITEM_LIST = "logItemList";
    private static final String CONTENT_TYPE = "application/x-protobuf";

    @Override
    protected byte[] buildRawBody(String uri, String providerId, Map<String, Object> bizParams, Map<String, Object> accessParams) {
        if (bizParams == null || bizParams.size() == 0) {
            return new byte[0];
        }
        JSONObject data = (JSONObject) bizParams;
        Logs.LogGroup.Builder logs = Logs.LogGroup.newBuilder();
        logs.setTopic(data.getString(LOG_TOPIC));
        logs.setSource(data.getString(LOG_SOURCE));
        List<LogItem> logItems = data.getJSONArray(LOG_ITEM_LIST).toJavaList(LogItem.class);
        for (LogItem item : logItems) {
            Logs.Log.Builder log = logs.addLogsBuilder();
            log.setTime(item.mLogTime);
            for (LogContent content : item.mContents) {
                CodingUtils.assertStringNotNullOrEmpty(content.mKey, "key");
                Logs.Log.Content.Builder contentBuilder = log.addContentsBuilder();
                contentBuilder.setKey(content.mKey);
                contentBuilder.setValue(content.mValue == null ? "" : content.mValue);
            }
        }
        Logs.LogGroup pbLog = logs.build();
        return pbLog.toByteArray();
    }

    @Override
    protected byte[] buildEncodeBody(String uri, String providerId, Map<String, Object> bizParams, Map<String, Object> accessParams, byte[] rawBody) {
        return LZ4Encoder.compressToLhLz4Chunk(rawBody.clone());
    }

    @Override
    protected Map<String, String> buildHeader(Method method, String uri, String providerId, Map<String, Object> bizParams,
                                              Map<String, Object> accessParams, byte[] rawBody, byte[] encodeBody) {
        Map<String, String> header = super.buildHeader(method, uri, providerId, bizParams, accessParams, rawBody, encodeBody);
        header.put("Content-Type", CONTENT_TYPE);
        header.put("x-log-compresstype", "lz4");
        return header;
    }
}
